let globalId = ''
// 获取列表数据
function getCategoryList() {
    request({
        type: 'get',
        url: '/admin/category/list',
        success: (res) => {
            const renderResult = template('cateItem', res)
            $('tbody').html(renderResult)
        }
    })
}
getCategoryList()

// 删除分类
$('tbody').on('click', '.delete', function(){
    const id = $(this).attr('data-id')
    request({
        type: 'post',
        url: '/admin/category/delete',
        data: { id },
        success: (res) => {
            if(res.code === 204){
                alert(res.msg)
                getCategoryList()
            }
        }
    })
})

// 点击新增
$('#xinzengfenlei').click(function () { 
    $('.add_category_wraper').show()
    $('#name').val('')
    $('#slug').val('')
});
// 点击编辑
$('tbody').on('click', '.edit', function () {
    const id = $(this).attr('data-id')
    globalId = id
    request({
        type: 'get',
        url: '/admin/category/search',
        data: { id },
        success: (res) => {
            if (res.code === 200) {
                $('.add_category_wraper').show()
                $('#name').val(res.data[0].name)
                $('#slug').val(res.data[0].slug)
            }
        }
    })
})
// 点击保存
$('.save').click(function () {
    const name = $('#name').val()
    const slug = $('#slug').val()
    if(globalId){
        request({
            type: 'post',
            url: '/admin/category/edit',
            data: { name, slug, id:globalId },
            success: (res) => {
                if(res.code === 200){
                    $('.add_category_wraper').hide()
                    getCategoryList()
                    globalId = ''
                }
            }
        })
    } else {
        request({
            type: 'post',
            url: '/admin/category/add',
            data: { name, slug },
            success: (res) => {
                if(res.code === 201){
                    $('.add_category_wraper').hide()
                    getCategoryList()
                }
            }
        })
    }
})
// 点击取消
$('.cancel').click(function () {
    $('.add_category_wraper').hide()
})